package indy.test.indy;

import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import indy.test.BlackBoxFileTransformer;
import indy.test.BlackBoxTest;

@BlackBoxTest
public class IndyBSMOneArgPrimitive implements BlackBoxFileTransformer {
    @Override
    public ClassVisitor transform(ClassVisitor cv) {
        return new ClassVisitor(Opcodes.ASM4, cv) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
                return new MethodVisitor(Opcodes.ASM4, mv) {
                    @Override
                    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
                        if ("indy".equals(name)) {
                            super.visitInvokeDynamicInsn("indy", desc,
                                    new Handle(Opcodes.H_INVOKESTATIC, owner, "bsm",
                                            MethodType.methodType(CallSite.class, Lookup.class, String.class, MethodType.class, int.class).toMethodDescriptorString()),
                                    42);
                            return;
                        }
                        super.visitMethodInsn(opcode, owner, name, desc);
                    }  
                };
            }
        };
    }
}
